package org.jeecg.modules.cw.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.cw.entity.*;
import org.jeecg.modules.cw.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 收支总表
 * @Author: jeecg-boot
 * @Date:   2025-10-24
 * @Version: V1.0
 */
@Api(tags="收支总表")
@RestController
@RequestMapping("/cw/cwSzzb")
@Slf4j
public class CwSzzbController extends JeecgController<CwSzzb, ICwSzzbService> {
	@Autowired
	private ICwSzzbService cwSzzbService;
	 @Autowired
	 private ICwApprovalMessageService cwApprovalMessageService;
	 @Autowired
	 private ICwXmzcsrbService cwXmzcsrbService;
	 @Autowired
	 private ISysDepartService sysDepartService;
	 @Autowired
	 private ISysBaseAPI iSysBaseAPI;
	 @Autowired
	 private ICwJbszqkzbService cwJbszqkzbService;
	/**
	 * 分页列表查询
	 *
	 * @param cwSzzb
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "收支总表-分页列表查询")
	@ApiOperation(value="收支总表-分页列表查询", notes="收支总表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CwSzzb>> queryPageList(CwSzzb cwSzzb,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CwSzzb> queryWrapper = QueryGenerator.initQueryWrapper(cwSzzb, req.getParameterMap());
		Page<CwSzzb> page = new Page<CwSzzb>(pageNo, pageSize);
		// 获取登录用户信息
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null || StringUtils.isEmpty(user.getId())) {
			return Result.error("未获取到登录用户信息，查询失败");
		}
		String currentUserId = user.getId();

		// 获取用户所属部门名称（departName）
		String departIdsByOrgCode = iSysBaseAPI.getDepartIdsByOrgCode(user.getOrgCode());
		SysDepart depart = sysDepartService.getById(departIdsByOrgCode);
		if (depart == null || StringUtils.isEmpty(depart.getDepartName())) {
			return Result.error("未获取到用户所属部门信息，查询失败");
		}
		String departName = depart.getDepartName(); // 用户所属部门名称

		// 定义特权用户ID
		String admin1 = "1985179654538330114";  // 第一个特权用户（拥有待审批权限）
		String admin2 = "1985180799365218306";  // 第二个特权用户
		String admin3 = "1985180919854989314";  // 第三个特权用户

		// 定义需要过滤的部门（机关、鉴定站）
		List<String> allowedDepartments = Arrays.asList("机关", "鉴定站");
		if (admin1.equals(currentUserId)) {
			// 第一个特权用户：
			// 1. 待审批状态仅查询“机关”和“鉴定站”部门
			// 2. 其他状态（通过、驳回、第一人审批同意）无部门限制
			queryWrapper.and(wrapper -> wrapper
					// 待审批 + 限定部门
					.or().eq("state", "待审批").in("unit", allowedDepartments)
					// 其他状态无部门限制
					.or().in("state", "通过", "驳回", "第一人审批同意")
			);
		} else if (admin2.equals(currentUserId) || admin3.equals(currentUserId)) {
			// 第二、三个特权用户：仅可查询通过、驳回
			queryWrapper.in("state", "通过", "驳回","第一人审批同意");
		} else {
			// 非特权用户：仅查询unit等于其所属部门名称的数据
			queryWrapper.eq("unit", departName);
		}
		IPage<CwSzzb> pageList = cwSzzbService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	 @ApiOperation(value = "按年度查询预算数据", notes = "按年度查询并返回计算后的预算数据")
	 @GetMapping(value = "/queryByYear")
	 public Result<List<CwSzzb>> queryByYear(CwSzzb cwSzzb) {
		 // 获取当前登录用户信息
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String orgCode = user.getOrgCode();
		 // 获取当前用户所属部门
		 String departIds = iSysBaseAPI.getDepartIdsByOrgCode(orgCode);
		 SysDepart depart = sysDepartService.getById(departIds);
		 if (depart == null) {
			 return Result.error("未查询到当前用户所属部门信息");
		 }
		 String departName = depart.getDepartName();
		 String year = cwSzzb.getYear();
		 if (year == null) {
			 return Result.error("年度参数不能为空");
		 }

		 // 1. 计算事业收入（sysr）、其他收入（qtsr）、使用非财政拨款结余（fc）
		 // 1.1 从CwXmzcsrb表计算
		 LambdaQueryWrapper<CwXmzcsrb> xmzcsrbWrapper = new LambdaQueryWrapper<>();
		 xmzcsrbWrapper.eq(CwXmzcsrb::getYear, year)
				 .eq(CwXmzcsrb::getUnit, departName);
		 List<CwXmzcsrb> xmzcsrbList = cwXmzcsrbService.list(xmzcsrbWrapper);
		 double a = 0.0, b = 0.0, c = 0.0; // a:事业收入累加，b:其他收入累加，c:非财政拨款结余累加
		 for (CwXmzcsrb entity : xmzcsrbList) {
			 a += (entity.getUndertakingRevenue() == null ? 0.0 : entity.getUndertakingRevenue());
			 b += (entity.getOtherRevenue() == null ? 0.0 : entity.getOtherRevenue());
			 c += (entity.getFczbkjy() == null ? 0.0 : entity.getFczbkjy());
		 }

		 // 1.2 从CwJbszqkzb表计算
		 LambdaQueryWrapper<CwJbszqkzb> jbszqkzbWrapper = new LambdaQueryWrapper<>();
		 jbszqkzbWrapper.eq(CwJbszqkzb::getYear, year)
				 .eq(CwJbszqkzb::getUnit, departName);
		 List<CwJbszqkzb> jbszqkzbList = cwJbszqkzbService.list(jbszqkzbWrapper);
		 double ysshj = 0.0, qtsrJb = 0.0, caizheng = 0.0,ltjf = 0.0,zfgjj=0.0,ryjf=0.0,gyfy=0.0;
		 for (CwJbszqkzb item : jbszqkzbList) {
			 if ("事业收入".equals(item.getProject())) {
				 ysshj = (item.getYsshj() == null ? 0.0 : item.getYsshj());
			 } else if ("其他收入".equals(item.getProject())) {
				 qtsrJb = (item.getYsshj() == null ? 0.0 : item.getYsshj());
			 } else if ("使用非财政拨款结余".equals(item.getProject())) {
				 caizheng = (item.getYsshj() == null ? 0.0 : item.getYsshj());
			 }
			 if ("离休费".equals(item.getProject())||"退休费".equals(item.getProject())||"退职役费".equals(item.getProject())
					 ||"抚恤金".equals(item.getProject())||"离退休人员".equals(item.getProject())||"生活补助".equals(item.getProject())
					 ||"救济费".equals(item.getProject())||"医疗费补助".equals(item.getProject())
					 ||"助学金".equals(item.getProject())
					 ||"个人农业生产补贴".equals(item.getProject())||"代缴社会保险费".equals(item.getProject())||"其他对个人和家庭的补助".equals(item.getProject())) {
				 ltjf += (item.getYsshj() == null ? 0.0 : item.getYsshj());
			 }
			 if ("住房公积金".equals(item.getProject())) {
				 zfgjj=(item.getYsshj() == null ? 0.0 : item.getYsshj());
			 }

			 if ("基本工资".equals(item.getProject())||"津贴补贴".equals(item.getProject())||"奖金".equals(item.getProject())||"伙食补助费".equals(item.getProject())||
					 "绩效工资".equals(item.getProject())||"机关事业单位基本养老保险缴费".equals(item.getProject())||"职业年金缴费".equals(item.getProject())||"职工基本医疗保险缴费".equals(item.getProject())||
					 "其他社会保障缴费".equals(item.getProject())||"医疗费".equals(item.getProject())||"其他工资福利支出".equals(item.getProject())
					 ||"其中在职人员".equals(item.getProject())||"奖励金".equals(item.getProject())){
				 ryjf=(item.getYsshj() == null ? 0.0 : item.getYsshj());
			 }

			 if ("房屋建筑物购建".equals(item.getProject())||"办公设备购置".equals(item.getProject())||"专用设备购置".equals(item.getProject())||"基础设施建设".equals(item.getProject())||
					 "大型修缮".equals(item.getProject())||"信息网络及软件购置更新".equals(item.getProject())||"物资储备".equals(item.getProject())||"土地补偿".equals(item.getProject())||
					 "安置补助".equals(item.getProject())||"地上附着物和青苗补偿".equals(item.getProject())||"拆迁补偿".equals(item.getProject())||"公务用车购置".equals(item.getProject())||
					 "其他交通工具购置".equals(item.getProject())||"文物和陈列品购置".equals(item.getProject())||"无形资产购置".equals(item.getProject())||"其他资本性支出".equals(item.getProject())||
					 "办公费".equals(item.getProject())||"印刷费".equals(item.getProject())||"手续费".equals(item.getProject())||"水费".equals(item.getProject())||
					 "电费".equals(item.getProject())||"邮电费".equals(item.getProject())||"其他交通费用".equals(item.getProject())||"税金及附加费用".equals(item.getProject())||
					 "其他商品和服务支出".equals(item.getProject())||"取暖费".equals(item.getProject())||"物业管理费".equals(item.getProject())||"差旅费".equals(item.getProject())||
					 "公务接待费".equals(item.getProject())||"专用材料费".equals(item.getProject())||"被装购置费".equals(item.getProject())||"专用燃料费".equals(item.getProject())||
					 "劳务费".equals(item.getProject())||"委托业务费".equals(item.getProject())||"工会经费".equals(item.getProject())||"租赁费".equals(item.getProject())||
					 "会议费".equals(item.getProject())||"培训费".equals(item.getProject())||"公务用车运行维护费".equals(item.getProject())||"因公出国境费用".equals(item.getProject())||
					 "维修护费".equals(item.getProject())){
				 gyfy=(item.getYsshj() == null ? 0.0 : item.getYsshj());
			 }
		 }

		 // 最终计算结果
		 double sysrTotal = a + ysshj;    // 事业收入总和
		 double qtsrTotal = b + qtsrJb;   // 其他收入总和
		 double fcTotal = c + caizheng;   // 使用非财政拨款结余总和

		 // 2. 查询当前年度+当前用户+当前部门的CwSzzb数据
		 QueryWrapper<CwSzzb> szzbWrapper = new QueryWrapper<>();
		 szzbWrapper.eq("year", year)
				 .eq("user_id", user.getId())
				 .eq("unit", departName); // 新增部门条件，确保数据归属正确
		 CwSzzb szzb = cwSzzbService.getOne(szzbWrapper);

		 // 3. 若数据不存在则新建，存在则更新计算字段
		 if (szzb == null) {
			 szzb = new CwSzzb();
			 szzb.setYear(year);
			 szzb.setUserId(user.getId());
			 szzb.setUnit(departName); // 保存部门信息，便于后续查询
			 szzb.setState("待提交");
			 szzb.setSysr(sysrTotal);    // 事业收入
			 szzb.setQtsr(qtsrTotal);    // 其他收入
			 szzb.setFc(fcTotal);        // 使用非财政拨款结余
			 szzb.setShbz(ltjf);
			 szzb.setZfbzzc(zfgjj);
			 szzb.setNkgg(ryjf+gyfy);
		 }else {
			 szzb.setSysr(sysrTotal);    // 事业收入
			 szzb.setQtsr(qtsrTotal);    // 其他收入
			 szzb.setFc(fcTotal);        // 使用非财政拨款结余
			 szzb.setShbz(ltjf);
			 szzb.setZfbzzc(zfgjj);
			 szzb.setNkgg(ryjf+gyfy);
		 }
		 List<CwSzzb> resultList = new ArrayList<>();
		 resultList.add(szzb);
		 // 4. 返回完整数据对象（包含所有字段）
		 return Result.OK(resultList);
	 }
	 /**
	  * 审批
	  * @param id 记录ID
	  * @return 处理结果
	  */
	 @AutoLog(value = "审批-审批")
	 @ApiOperation(value="审批-审批", notes="审批-审批")
	 @RequestMapping(value = "/approval", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> approval(@RequestParam String id,
									@RequestParam String approvalResult,
									@RequestParam String approvalRemark) {
		 //获取当前用户名
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userId=user.getId();
		 CwSzzb byId = cwSzzbService.getById(id);
		 CwApprovalMessage cwApprovalMessage = new CwApprovalMessage();
		 cwApprovalMessage.setMainId(byId.getId());
		 cwApprovalMessage.setApprovalMessage(approvalRemark);
		 cwApprovalMessage.setApprovalTime(new Date());
		 cwApprovalMessage.setApprover(userId);
		 cwApprovalMessage.setState(approvalResult);
		 cwApprovalMessage.setSpr(user.getRealname());
		 cwApprovalMessageService.save(cwApprovalMessage);
		 if ("通过".equals(approvalResult)) {
			 if ("1985179754371153921".equals(userId)||"1985179977394880513".equals(userId)||
					 "1985180115760775170".equals(userId)||"1985180266818633730".equals(userId)
					 ||"1985180455415513090".equals(userId)){
				 byId.setState("第一人审批同意");
			 }else {
				 byId.setState(approvalResult);
			 }
		 }else {
			 byId.setState(approvalResult);
		 }
		 cwSzzbService.updateById(byId);
		 return Result.OK("提交成功");
	 }

	 /**
	  * 提交处理
	  * @param id 记录ID
	  * @return 处理结果
	  */
	 @AutoLog(value = "提交-提交")
	 @ApiOperation(value="提交-提交", notes="提交-提交")
	 @RequestMapping(value = "/tj", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> tj(@RequestParam String id) {
		 //获取当前用户名
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userName=user.getRealname();
		 log.info(id);
		 CwSzzb byId = cwSzzbService.getById(id);
		 byId.setState("待审批");
		 cwSzzbService.updateById(byId);
		 return Result.OK("提交成功");
	 }
	/**
	 *   添加
	 *
	 * @param cwSzzb
	 * @return
	 */
	@AutoLog(value = "收支总表-添加")
	@ApiOperation(value="收支总表-添加", notes="收支总表-添加")
	//@RequiresPermissions("org.jeecg.modules:cw_szzb:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CwSzzb cwSzzb) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departIdsByOrgCode = iSysBaseAPI.getDepartIdsByOrgCode(user.getOrgCode());
		SysDepart byId = sysDepartService.getById(departIdsByOrgCode);
		String departName = byId.getDepartName();
		cwSzzb.setUnit(departName);
		cwSzzb.setUserId(user.getId());
		cwSzzb.setState("待提交");
		cwSzzbService.save(cwSzzb);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cwSzzb
	 * @return
	 */
	@AutoLog(value = "收支总表-编辑")
	@ApiOperation(value="收支总表-编辑", notes="收支总表-编辑")
	//@RequiresPermissions("org.jeecg.modules:cw_szzb:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CwSzzb cwSzzb) {
		CwSzzb byId = cwSzzbService.getById(cwSzzb.getId());
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		cwSzzb.setUserId(user.getId());
		cwSzzb.setState(byId.getState());
		cwSzzbService.updateById(cwSzzb);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "收支总表-通过id删除")
	@ApiOperation(value="收支总表-通过id删除", notes="收支总表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:cw_szzb:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cwSzzbService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "收支总表-批量删除")
	@ApiOperation(value="收支总表-批量删除", notes="收支总表-批量删除")
	//@RequiresPermissions("org.jeecg.modules:cw_szzb:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cwSzzbService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "收支总表-通过id查询")
	@ApiOperation(value="收支总表-通过id查询", notes="收支总表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CwSzzb> queryById(@RequestParam(name="id",required=true) String id) {
		CwSzzb cwSzzb = cwSzzbService.getById(id);
		if(cwSzzb==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cwSzzb);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cwSzzb
    */
    //@RequiresPermissions("org.jeecg.modules:cw_szzb:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CwSzzb cwSzzb) {
        return super.exportXls(request, cwSzzb, CwSzzb.class, "收支总表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("cw_szzb:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CwSzzb.class);
    }

}
